package com.example.mybatisplus.realm;

import com.example.mybatisplus.model.domain.Role;
import com.example.mybatisplus.model.domain.User;

import com.example.mybatisplus.service.RoleService;
import com.example.mybatisplus.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("开始授权");
        //获取登录用户名
        String username= (String) SecurityUtils.getSubject().getPrincipal();

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();

        Set<String> roles=new HashSet<>();
        //根据用户名去数据库查询用户信息
        Role role =roleService.getRolebyName(username);
        System.out.println(role.getRoleName());
        //添加角色和权限

        roles.add(role.getRoleName());
        info.setRoles(roles);
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("开始认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//        principal.setRememberMe(true);
        String password =userService.getUserbyName(token.getUsername()).getStuPassword();

        if (null == password) {
            throw new AccountException("用户名不正确");
        } else if (!password.equals(new String((char[]) token.getCredentials()))) {
            throw new AccountException("密码不正确");
        }

        //获取用户信息
        String name = token.getUsername();
        User user = userService.getUserbyName(name);
        System.out.println(user);

        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }

        return new SimpleAuthenticationInfo(token.getPrincipal(), password, getName());
    }
}
